package com.janko.springbootbase.juc;


import java.util.concurrent.TimeUnit;

/**
 * 面试题：模拟银行账户
 * 对业务写方法加锁
 * 对业务读方法不加锁
 *
 * 容易产生脏读问题（dirtyRead）
 */
public class SynchronizedAccount_DirtyRead {
    String name;
    double balance;

    /**
     * 在线程沉睡过程中，会产生脏读的业务情况
     */
    public synchronized void set(String name, double balance) {
        this.name = name;

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.balance = balance;
    }

    /**
     * 如果不添加 Synchronized的时候，会出现脏读
     */
    public /*synchronized*/ double getBalance(String name) {
        return this.balance;
    }


    public static void main(String[] args) {
        SynchronizedAccount_DirtyRead account = new SynchronizedAccount_DirtyRead();
        new Thread(()->account.set("zhangsan", 100.0)).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(account.getBalance("zhangsan"));

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(account.getBalance("zhangsan"));
    }
}
